require(['./config'], () => {
  require(['jquery', 'Zoom', 'Product', 'template', 'Shortcut'], ($, Zoom, Product, template, Shortcut) => {
    // 详情页事件
    class detail {
      constructor () {
        this.loadPublic()
        this.getData().then(() => {
          this.render()
          // 初始化放大镜事件
          new Zoom($('.product-gallery-img')[0], $('.product-gallery-img-big')[0])
          // 初始化商品交互
          new Product(this.body)
          // 初始购物车交互
          new Shortcut
        })

        this.navMainLastIndex = 0
        this.thumbsLastIndex = 0
      }

      loadPublic () {
        const _this = this
        $('.shortcut').load('/HTML/shortcut.html')
        $('.footer').load('/HTML/footer.html')
        $('.sidebar').load('/HTML/sidebar.html')
        $('.header').load('/HTML/header.html', () => {
          $('.nav-class').show()
            .on('mouseenter', function () {
              $('.category').show()
              $('.category-item').eq(0).addClass('active')
            })
            .on('mouseleave', function () {
              $('.category').hide()
              $('.category-item').removeClass('active')
            })
          $('.category').load('/HTML/nav.html', function () {
            $(this).hide().addClass('detail')
            _this.showNavMoreEvent()
          })
        })
      }

      showNavMoreEvent () {
        const _this = this
        $('.category-item')
          .on('mouseenter', function () {
            $('.category-item').eq(_this.navMainLastIndex).removeClass('active')
            $(this).addClass('active')
          })
          .on('mouseleave', function () {
            _this.navMainLastIndex = $(this).index()
          })
      }

      getData () {
        // 从地址栏拿到id，根据id请求数据
        const id = window.location.search.slice(1).split('&').reduce((obj, item) => {
          let arr = item.split('=')
          obj[arr[0]] = arr[1]
          return obj
        }, {}).id
        return new Promise(resolve => {
          $.get('/api/detail', { id: Number(id) }, res => {
            this.body = res.body
            resolve()
          })
        })
      }

      render () {
        $('#shop').html(template('shopTemplate', this.body))
        console.log(this.body)
      }
    }

    new detail()
  })
})
